package com.rrqs.activity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zadtek.xmqishi.R;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.QiangDanData;
import com.rrqs.activity.data.SygOrdetailData;
import com.rrqs.frame.JsonProcessHelper;

/**
 * 随意购订单详情
 *
 * @author kuyukeji
 */
@EActivity(R.layout.syg_order_detail)
public class SygOrdDetailActivity extends BaseActivity {

    @ViewById
    ImageView backid;

    @ViewById
    TextView topview, beizhu, order_main, ordpaysta; // 标题,备注,订单号,支付方式

    @ViewById
    TextView typename, ordxdtime, wpname; // 类型名称,订单时间,物品信息

    @ViewById
    TextView psmy, xiaofmy, goods_mj_memoy, totalmy; // 配送费,小费,优惠金额,总计

    @ViewById
    TextView fromaddr, sendaddr, fromdistvw, todistvw;    // 购买/取货地址,收货地址,距离

    @ViewById
    TextView tsname; // 帮你买的提示信息
    @ViewById
    RelativeLayout djq_layout; // 使用优惠券的面板
    @ViewById
    LinearLayout fromaddrlay, address_layout, beizhulay;// 购买/取货地址面板,收货面板,备注面板
    @ViewById
    ImageView fromicon; // 购买/发/取的图标

    @ViewById
    Button calluser, ordover; // 联系顾客,订单状态

    @ViewById
    TextView jiedtime, qhuotime, wanctime, pstimes; // 接单时间,取货,完成, 配送耗时
    @ViewById
    LinearLayout orderwclay; // 配送完成底部的面板

    private SharedPreferences sp; // 用户信息缓存
    private Handler mHandler;
    private Dialog dialog;
    private Resources res;

    private SygOrdetailData detaildata; // 订单详情

    private String orderid; // 订单号
    private String fromdist = "", todist = "";    //距离字段

    // 初始化
    @AfterViews
    void initViews() {
        topview.setText("万能跑腿订单详情");
        orderwclay.setVisibility(View.GONE);
    }

    @Click(R.id.backid)
    void backonclik() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        res = getResources();
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            orderid = bundle.getString("mainid");
            fromdist = bundle.getString("location_get");
            todist = bundle.getString("location");
            dialog = Common.getTipDialog(SygOrdDetailActivity.this,
                    R.layout.loading, 0, 0);
            new myAsyncTask().execute("getdetail", orderid);
        }

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS: // 成功
                        closeDialog();
                        detaildata = (SygOrdetailData) msg.obj;
                        String retstatus = detaildata.getRet();
                        if (retstatus != null && retstatus.equals("200")) {
                            order_main.setText("订单号：" + detaildata.getOrder_id());

                            String payvar = "支付宝支付";
                            String paytype = detaildata.getPaytype();
                            if (paytype != null && !paytype.equals("")) {
                                if (paytype.equals("0")) {
                                    payvar = "货到付款";
                                } else if (paytype.equals("1") || paytype.equals("3")) {
                                    payvar = "支付宝支付";
                                } else if (paytype.equals("2")) {
                                    payvar = "微信支付";
                                }
                            }
                            ordpaysta.setText(payvar);

                            String ordmark = detaildata.getOrder_mark();
                            if (ordmark != null && !ordmark.equals("")) {
                                beizhulay.setVisibility(View.VISIBLE);
                                beizhu.setText(ordmark);
                            } else {
                                beizhulay.setVisibility(View.GONE);
                            }

                            String type = detaildata.getType();
                            if (type.equals("buy")) {// 买
                                typename.setText("帮你买");
                                tsname.setVisibility(View.VISIBLE);
                                fromicon.setBackgroundDrawable(res
                                        .getDrawable(R.drawable.gou));
                                String buyaddr = detaildata.getBuy_addr();
                                String showbuyaddr = "";
                                if (buyaddr != null && !buyaddr.equals("")
                                        && !buyaddr.equals("null")) {
                                    fromaddrlay.setVisibility(View.VISIBLE);
                                    showbuyaddr = buyaddr;
                                }
                                String buyroad = detaildata.getBuy_road();
                                if (buyroad != null && !buyroad.equals("")
                                        && !buyroad.equals("null")) {
                                    fromaddrlay.setVisibility(View.VISIBLE);
                                    showbuyaddr = showbuyaddr + "  " + buyroad;
                                }
                                fromaddr.setText(showbuyaddr);

                            } else if (type.equals("send")) {// 送
                                typename.setText("帮你送");
                                tsname.setVisibility(View.GONE);
                                fromaddrlay.setVisibility(View.VISIBLE);
                                fromicon.setBackgroundDrawable(res
                                        .getDrawable(R.drawable.fa));
                                fromaddr.setText(detaildata.getGet_addr() + "  "
                                        + detaildata.getGet_road());

                            } else if (type.equals("get")) {// 取
                                typename.setText("帮你取");
                                tsname.setVisibility(View.GONE);
                                fromaddrlay.setVisibility(View.VISIBLE);
                                fromicon.setBackgroundDrawable(res
                                        .getDrawable(R.drawable.qu));
                                fromaddr.setText(detaildata.getGet_addr() + "  "
                                        + detaildata.getGet_road());
                            }
                            sendaddr.setText(detaildata.getAddress() + "  "
                                    + detaildata.getMap_location());
                            ordxdtime.setText(detaildata.getAdd_time());

                            if (fromdist != null && !fromdist.equals("")
                                    && !fromdist.equals("0")) {
                                fromdistvw.setText(fromdist + "km");
                            } else {
                                fromdistvw.setVisibility(View.GONE);
                            }
                            if (todist != null && !todist.equals("")
                                    && !todist.equals("0")) {
                                todistvw.setText(todist + "km");
                            } else {
                                todistvw.setVisibility(View.GONE);
                            }

                            String wupname = detaildata.getTitle();
                            String price = detaildata.getPrice();
                            if (price != null && !price.equals("")) {
                                if (Float.parseFloat(price) > 0) {
                                    wupname = wupname + "\n商品预期价格￥" + price;
                                }
                            }
                            wpname.setText(wupname);
                            psmy.setText("¥" + detaildata.getShipping_fee());
                            xiaofmy.setText("¥" + detaildata.getFee());
                            totalmy.setText("¥" + detaildata.getTotal_fee());
                            String youhje = detaildata.getVoucher_fee();
                            if (youhje != null && !youhje.equals("")) {
                                if (Float.parseFloat(youhje) > 0) {
                                    djq_layout.setVisibility(View.VISIBLE);
                                    goods_mj_memoy.setText("-¥" + youhje);
                                }
                            }

                            calluser.setTag(detaildata.getPhone());

                            String mainstatus = detaildata.getStatus();
                            if (mainstatus.equals("9")) {
                                ordover.setText("已完成");
                                ordover.setBackgroundDrawable(getResources()
                                        .getDrawable(R.drawable.order_over));

                                orderwclay.setVisibility(View.VISIBLE);
                                jiedtime.setText(detaildata.getCheck_time());
                                qhuotime.setText(detaildata.getGet_time());
                                wanctime.setText(detaildata.getSend_time());
                                pstimes.setText("配送耗时：" + detaildata.getSpendtime()
                                        + "分钟");
                                fromaddrlay.setVisibility(View.GONE);
                                address_layout.setVisibility(View.GONE);

                            } else {
                                orderwclay.setVisibility(View.GONE);
                                if (mainstatus.equals("6")) { // 未取货
                                    ordover.setText("确认取货");
                                    ordover.setBackgroundDrawable(getResources()
                                            .getDrawable(R.drawable.orderpsbut));
                                } else if (mainstatus.equals("7")) { // 已取货,配送中
                                    ordover.setText("确认送达");
                                    ordover.setBackgroundDrawable(getResources()
                                            .getDrawable(R.drawable.order_over));
                                } else if (mainstatus.equals("11")) { // 已取消
                                    ordover.setText("已取消");
                                    ordover.setBackgroundDrawable(getResources()
                                            .getDrawable(R.drawable.order_over));
                                } else if (mainstatus.equals("8")) {
                                    ordover.setText("已送达");
                                } else if (mainstatus.equals("10")) {
                                    ordover.setText("已评价");
                                } else if (mainstatus.equals("12")) {
                                    ordover.setText("待确认");
                                } else if (mainstatus.equals("13")) {
                                    ordover.setText("商家已接单");
                                }
                            }

                        } else {
                            Common.DisplayToast(SygOrdDetailActivity.this,
                                    detaildata.getMsg(), 2);
                            finish();
                        }
                        break;
                    case Const.STATE_START_ERROR:
                        closeDialog();
                        Common.DisplayToast(SygOrdDetailActivity.this,
                                "通信失败,请检查网络!", 2);
                        finish();
                        break;
                    case Const.STATE_START_QIANG: // 确认取货成功
                        closeDialog();
                        QiangDanData gethdata = (QiangDanData) msg.obj;
                        String qhstatus = gethdata.getStatus();
                        if (qhstatus != null && qhstatus.equals("200")) {//成功
                            detaildata.setStatus("6");
                            ordover.setText("确认送达");
                            ordover.setBackgroundDrawable(getResources()
                                    .getDrawable(R.drawable.order_over));
                        }
                        Common.DisplayToast(SygOrdDetailActivity.this,
                                gethdata.getMessage(), 2);
                        break;
                }
            }
        };

    }

    public class myAsyncTask extends AsyncTask<String, String, String> {

        private SygOrdetailData datas;
        private QiangDanData getfdata; // 确认取货

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String res = "";
            if (params[0].equals("getdetail")) {
                sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");
                datas = JsonProcessHelper.jsonProcess_sygorderinfo(
                        "get_order_info", params[1], uid);
                if (null != datas) {
                    res = "getok";
                } else {
                    res = "ping_me_error";
                }

            } else if (params[0].equals("getfood")) { // 确认取货
                sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");
                getfdata = JsonProcessHelper.jsonProcess_getexgetfood(
                        "ex_get_food", params[1], uid, params[2]);
                if (null != getfdata) {
                    res = "getfoodok";
                } else {
                    res = "ping_me_error";
                }
            }

            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result.equals("getok")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_SUCCESS;
                msg.obj = datas;
                mHandler.sendMessage(msg);
            } else if (result.equals("ping_me_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_ERROR;
                mHandler.sendMessage(msg);
            } else if (result.equals("getfoodok")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_QIANG;
                msg.obj = getfdata;
                mHandler.sendMessage(msg);
            }
        }
    }

    // 关闭dialog
    void closeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    //执行确认取货
    @Click(R.id.ordover)
    void execQuhuo() {
        if (detaildata.getStatus().equals("6")) { // 确认取货
            dialog = Common.getTipDialog(
                    SygOrdDetailActivity.this,
                    R.layout.loading, 0, 0);
            String type = detaildata.getType();
            if (type.equals("buy")) {// 买
                new myAsyncTask().execute("getfood", orderid, "1");
            } else if (type.equals("send")) {// 送
                new myAsyncTask().execute("getfood", orderid, "2");
            } else if (type.equals("get")) {// 取
                new myAsyncTask().execute("getfood", orderid, "3");
            }
        }
    }

    //顾客电话
    @Click(R.id.calluser)
    void callUserphone() {
        if (!calluser.getTag().toString().equals("null")
                && !calluser.getTag().toString().equals("")) {
            callPhoneNumber(calluser.getTag().toString());
        } else {
            Common.DisplayToast(SygOrdDetailActivity.this, "手机号码为空！", 1);
        }
    }

    // 电话
    public void callPhoneNumber(String phoneNumber) {
        if (phoneNumber != null && !phoneNumber.equals("")) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    }

    //购买/取货地址导航
    @Click(R.id.fromaddrlay)
    void tobuyquAddress() {
        String lat = "0.0", lng = "0.0";
        String type = detaildata.getType();
        if (type.equals("buy")) {// 买
            lat = detaildata.getBuy_lat();
            lng = detaildata.getBuy_lng();
        } else {//送取
            lat = detaildata.getGet_lat();
            lng = detaildata.getGet_lng();
        }
        if (!lat.equals("0.0") && null != lat && !lng.equals("0.0")
                && null != lng && !lat.equals("null") && !lng.equals("null")) {
            Intent intent = new Intent(this, MyMapLocation.class);
            intent.putExtra("lat", lat);
            intent.putExtra("lng", lng);
            startActivity(intent);
        } else {
            Common.DisplayToast(SygOrdDetailActivity.this, "坐标获取失败！", 2);
        }
    }

    //送货地址导航
    @Click(R.id.address_layout)
    void tosendAddress() {
        String lat = "0.0", lng = "0.0";
        lat = detaildata.getSend_lat();
        lng = detaildata.getSend_lng();
        if (!lat.equals("0.0") && null != lat && !lng.equals("0.0")
                && null != lng && !lat.equals("null") && !lng.equals("null")) {
            Intent intent = new Intent(this, MyMapLocation.class);
            intent.putExtra("lat", lat);
            intent.putExtra("lng", lng);
            startActivity(intent);
        } else {
            Common.DisplayToast(SygOrdDetailActivity.this, "坐标获取失败！", 2);
        }
    }

}
